<?php
require_once '../library/Auth/OAuth2/Client.php';
require_once '../library/Auth/OAuth2/GrantType/IGrantType.php';
require_once '../library/Auth/OAuth2/GrantType/AuthorizationCode.php';

const CLIENT_ID     = '64670291c908100628d4e8254dbbb3c8488d79eb97d1045b915c5263caa6ff77';
const CLIENT_SECRET = 'cef8bf16840c94bdfc6e0fe2ebc15f400c9588dbaa0fb72762010815f222b8a3';

const REDIRECT_URI           = 'http://blog.saio.vn/index/callback';
const AUTHORIZATION_ENDPOINT = 'http://localhost:3000/oauth/authorize';
const TOKEN_ENDPOINT         = 'http://localhost:3000/oauth/token';

class MCore_OAuth {
	protected $client = null;

	function __construct() {
		$this->client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET);
	}

	public function getCode(){
		try{
			$code = null;
			if(empty($_SESSION['oauth_code'])){
				$authUrl = $this->client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
				$oauthClient = new Zend_Http_Client($authUrl);
				$response = $oauthClient->request('GET');
				$code = $response->getBody();
				switch($code){
					case 'The redirect uri included is not valid.':
						return null;
					break;
					default:
						$_SESSION['oauth_code'] = $code;
					break;
				}				
			}else{
				$code = $_SESSION['oauth_code'];
			}
			return $code;
		}catch(Exception $e){
			return null;
		}
	}

	public function getApi($url, $params = null, $method =  OAuth2\Client::HTTP_METHOD_GET, $timeout = 0){
		if($timeout >= 2){
			return null;
		}
		$result = null;
		$code = $this->getCode();
		if(!$code)
			return $result;

		if($params != null){
			$params['code'] = $code;
			$params['redirect_uri'] = REDIRECT_URI;
		}else{
			$params = array('code' => $code, 'redirect_uri' => REDIRECT_URI);
		}
	    $response = $this->client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params);
	    if (!empty($response['result']['error']) && !empty($response['result']['error_description'])){
	    	switch ($response['result']['error_description']) {
	    		case 'The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.':
	    		unset($_SESSION['oauth_code']);
	    		$result = $this->getApi($url, $params, $method, $timeout + 1);
	    		break;
	    	}
	    }else if(!empty($response['result']['access_token'])){
		    $info = $response['result'];
		    $this->client->setAccessToken($info['access_token']);
		    $response = $this->client->fetch($url, $params, $method);
		    $result = $response['result'];
		}
	    return $result;		
	}

}